<template>
  <div>
    <el-container style="height: 100vh; border: none; margin: 0; padding: 0;">
      <el-header style="font-size: 40px; background-color: rgb(238, 241, 246)">
        <div class="header-left">
          <span>书缘校园-校园二手书交流系统</span>
        </div>
        <div class="header-right">
          <router-link to="/mySetting">
            <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
          </router-link>
        </div>
      </el-header>
      <el-container>
        <aside-layout></aside-layout>
        <el-main
          style="margin: 0; padding: 20px; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);">
          <!-- 搜索框、搜索按钮和分类框 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-input placeholder="搜索书名或作者" v-model="searchQuery" clearable @clear="fetchBooks"
                style="border-radius: 20px;"></el-input>
            </el-col>
            <el-col :span="6">
              <el-button type="primary" @click="handleSearch" style="width: 100%; border-radius: 20px;">搜索</el-button>
            </el-col>
            <el-col :span="6">
              <el-select v-model="selectedCategory" placeholder="选择分类" @change="fetchBooks"
                style="width: 100%; border-radius: 20px;">
                <el-option label="所有分类" value=""></el-option>
                <el-option label="小说" value="小说"></el-option>
                <el-option label="教材" value="教材"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-col>
          </el-row>

          <!-- ECharts 图表展示 -->
          <el-row style="margin-top: 20px;">
            <el-col :span="12">
              <h2 style="color: #333;">书籍分类分布</h2>
              <div ref="pieChart" style="width: 100%; height: 300px;"></div>
            </el-col>
            <el-col :span="12">
              <h2 style="color: #333;">书籍价格分布</h2>
              <div ref="barChart" style="width: 100%; height: 300px;"></div>
            </el-col>
          </el-row>

          <!-- 书籍列表 -->
          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col v-for="book in books" :key="book.id" :span="6">
              <el-card :body-style="{ padding: '20px' }" @click="openBookDetails(book)"
                style="border-radius: 10px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); transition: transform 0.2s;">
                <img :src="book.cover" class="book-cover" />
                <div class="book-info">
                  <h3 style="font-size: 18px; color: #333;">{{ book.name }}</h3>
                  <p style="color: #666;">{{ book.intro }}</p>
                  <p style="color: #e74c3c;">价格: {{ book.price }}元</p>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <!-- 分页 -->
          <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="totalBooks" style="margin-top: 20px;">
          </el-pagination>

          <!-- 推荐书籍 -->
          <div style="margin-top: 40px;">
            <h2 style="color: #333;">推荐书籍</h2>
            <el-row :gutter="20">
              <el-col v-for="book in recommendedBooks" :key="book.id" :span="6">
                <el-card :body-style="{ padding: '20px' }" @click="openBookDetails(book)"
                  style="border-radius: 10px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);">
                  <img :src="book.cover" class="book-cover" />
                  <div class="book-info">
                    <h3 style="font-size: 18px; color: #333;">{{ book.name }}</h3>
                    <p style="color: #e74c3c;">价格: {{ book.price }}元</p>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>

          <!-- 热门书籍 -->
          <div style="margin-top: 40px;">
            <h2 style="color: #333;">热门书籍</h2>
            <el-row :gutter="20">
              <el-col v-for="book in popularBooks" :key="book.id" :span="6">
                <el-card :body-style="{ padding: '20px' }" @click="openBookDetails(book)"
                  style="border-radius: 10px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);">
                  <img :src="book.cover" class="book-cover" />
                  <div class="book-info">
                    <h3 style="font-size: 18px; color: #333;">{{ book.name }}</h3>
                    <p style="color: #e74c3c;">价格: {{ book.price }}元</p>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>

          <!-- 用户评价 -->
          <div style="margin-top: 40px;">
            <h2 style="color: #333;">用户评价</h2>
            <el-card v-for="review in userReviews" :key="review.id"
              style="margin-bottom: 20px; border-radius: 10px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);">
              <div>
                <strong style="color: #333;">{{ review.user }}</strong>
                <p style="color: #666;">{{ review.comment }}</p>
              </div>
            </el-card>
          </div>

          <!-- 书籍详情弹窗 -->
          <el-dialog :visible.sync="dialogVisible" title="书籍详情">
            <div v-if="selectedBook">
              <img :src="selectedBook.cover" class="book-cover" />
              <h3 style="color: #333;">{{ selectedBook.name }}</h3>
              <p style="color: #666;">{{ selectedBook.intro }}</p>
              <p style="color: #e74c3c;">价格: {{ selectedBook.price }}元</p>
            </div>
          </el-dialog>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import AsideLayout from '../../layout/AsideLayout.vue';

export default {
  components: { AsideLayout },
  data() {
    return {
      searchQuery: '',
      selectedCategory: '',
      books: [], // 所有书籍数据
      recommendedBooks: [], // 推荐书籍数据
      popularBooks: [], // 热门书籍数据
      userReviews: [], // 用户评价数据
      currentPage: 1,
      pageSize: 10,
      totalBooks: 0, // 根据实际书籍数量更新
      dialogVisible: false,
      selectedBook: null,
    };
  },
  methods: {
    async fetchBooks() {
      try {
        const query = this.searchQuery;
        const category = this.selectedCategory;
        const response = await fetch(`http://localhost:3000/api/books?query=${query}&category=${category}&page=${this.currentPage}&size=${this.pageSize}`);
        const data = await response.json();

        // 确保后端返回的数据结构为 { books: [], total: 10 }
        this.books = data.books; // 更新书籍数据
        this.totalBooks = data.total; // 更新总书籍数量
        this.renderCharts(); // 更新图表数据
      } catch (error) {
        console.error('Error fetching books:', error);
      }
    },
    async fetchRecommendedBooks() {
      try {
        const response = await fetch('http://localhost:3000/api/recommended-books');
        const data = await response.json();
        this.recommendedBooks = data.recommendedBooks;
      } catch (error) {
        console.error('Error fetching recommended books:', error);
      }
    },
    async fetchUserReviews() {
      try {
        const response = await fetch('http://localhost:3000/api/reviews');
        const data = await response.json();
        this.userReviews = data.userReviews;
      } catch (error) {
        console.error('Error fetching user reviews:', error);
      }
    },
    async fetchPopularBooks() {
      try {
        const response = await fetch('http://localhost:3000/api/popular-books');
        const data = await response.json();
        this.popularBooks = data.popularBooks;
      } catch (error) {
        console.error('Error fetching popular books:', error);
      }
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.fetchBooks();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchBooks();
    },
    openBookDetails(book) {
      this.selectedBook = book;
      this.dialogVisible = true;
    },
    renderCharts() {
      // 初始化饼图
      const pieChart = echarts.init(this.$refs.pieChart);
      const categoryData = this.books.reduce((acc, book) => {
        const category = book.category;
        acc[category] = (acc[category] || 0) + 1;
        return acc;
      }, {});
      const pieData = Object.keys(categoryData).map(key => ({
        name: key,
        value: categoryData[key],
      }));
      pieChart.setOption({
        title: {
          text: '书籍分类分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        series: [
          {
            name: '书籍分类',
            type: 'pie',
            radius: '50%',
            data: pieData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      });

      // 初始化柱状图
      const barChart = echarts.init(this.$refs.barChart);
      const priceRanges = [
        { range: '0-50元', min: 0, max: 50 },
        { range: '51-100元', min: 51, max: 100 },
        { range: '101-150元', min: 101, max: 150 },
        { range: '151元以上', min: 151, max: Infinity },
      ];
      const barData = priceRanges.map(range => ({
        name: range.range,
        value: this.books.filter(book => book.price >= range.min && book.price <= range.max).length,
      }));
      barChart.setOption({
        title: {
          text: '书籍价格分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        xAxis: {
          type: 'category',
          data: barData.map(item => item.name)
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '书籍数量',
            type: 'bar',
            data: barData.map(item => item.value),
            itemStyle: {
              color: '#42A5F5'
            }
          }
        ]
      });
    },
    // 添加 handleSearch 方法
    handleSearch() {
      this.fetchBooks();
    }
  },
  mounted() {
    this.fetchBooks();
    this.fetchRecommendedBooks();
    this.fetchUserReviews();
    this.fetchPopularBooks();
  }
};
</script>

<style>
.book-cover {
  width: 100%;
  height: auto;
  border-radius: 5px;
}

.book-info {
  margin-top: 10px;
}

.header-left {
  font-weight: bold;
}

.el-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-container {
  height: 100%;
}

.el-main {
  padding: 20px;
}

.el-card {
  cursor: pointer;
  transition: transform 0.2s;
}

.el-card:hover {
  transform: scale(1.05);
}
</style>